package com.tech.arno.spicysdk.videosdk.core.slot;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.tech.arno.spicysdk.videosdk.activity.AdBrowserActivity;
import com.tech.arno.spicysdk.videosdk.constant.SDKConstant;
import com.tech.arno.spicysdk.videosdk.core.AdContextParameters;
import com.tech.arno.spicysdk.videosdk.module.AdValue;
import com.tech.arno.spicysdk.videosdk.report.ReportManager;
import com.tech.arno.spicysdk.videosdk.widget.CustomVideoView;
import com.tech.arno.spicysdk.videosdk.widget.VideoFullDialog;
import com.util.Utils;


/**
 * @author: qndroid
 * @function: 广告业务逻辑层
 * @date: 16/6/20
 */
public class VideoSDKSlot implements CustomVideoView.ADVideoPlayerListener {

    private Context mContext;
    /**
     * UI
     */
    private CustomVideoView mVideoView;
    private ViewGroup mParentView;//要添加的父容器
    /**
     * Data
     */
    private AdValue mXAdInstance;
    private VideoSDKSlotListener mSlotListener;
    private boolean canPause = false; //是否可自动暂停标志位
    private boolean isFirst = false;
    private int lastArea = 0; //防止将要滑入滑出时播放器的状态改变

    public VideoSDKSlot(AdValue adInstance,
                        VideoSDKSlotListener slotLitener, CustomVideoView.ADFrameImageLoadListener frameLoadListener) {
        this.mXAdInstance = adInstance;
        this.mSlotListener = slotLitener;
        this.mParentView = slotLitener.getAdParent();
        this.mContext = mParentView.getContext();
        initVideoView(frameLoadListener);
    }

    private void initVideoView(CustomVideoView.ADFrameImageLoadListener frameImageLoadListener) {

        mVideoView = new CustomVideoView(mContext, mParentView);
        if (mXAdInstance != null) {
            mVideoView.setDataSource(mXAdInstance.resource);
            mVideoView.setFrameURI(mXAdInstance.thumb);
            mVideoView.setFrameLoadListener(frameImageLoadListener);
            mVideoView.setListener(this);
        }
        RelativeLayout paddingView = new RelativeLayout(mContext);
        paddingView.setBackgroundColor(mContext.getResources().getColor(android.R.color.black));
        paddingView.setLayoutParams(mVideoView.getLayoutParams());
        mParentView.addView(paddingView);
        mParentView.addView(mVideoView);
    }

    private boolean isPlaying() {
        if (mVideoView != null) {
            return mVideoView.isPlaying();
        }
        return false;
    }

    private boolean isPauseBtnClick() {
        if (mVideoView != null) {
            return mVideoView.isPauseBtnClicked();
        }
        return false;
    }

    private boolean isComplete() {
        if (mVideoView != null) {
            return mVideoView.isComplete();
        }
        return false;
    }

    //pause the  video
    private void pauseVideo(boolean isAuto) {
        if (mVideoView != null) {
            if (isAuto) {
                //发自动暂停监测
                if (!isPauseBtnClick() && isPlaying()) {
                    try {
                        ReportManager.pauseVideoReport(mXAdInstance.event.pause.content, getPosition());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            mVideoView.seekAndPause(0);
        }
    }

    //resume the video
    private void resumeVideo() {
        if (mVideoView != null) {
            mVideoView.resume();
            if (isPlaying() && isFirst) {
                isFirst = false;
                sendSUSReport(true); //发自动播放监测
            }
        }
    }

    /**
     * @name updateVideoInScrollView
     * @function 实现划入播放画出暂停
     * @author ArnoFrost
     * @time 2017/12/14 0014  10:14
     */
    public void updateVideoInScrollView() {
        int currentArea = Utils.getVisiblePercent(mParentView);
        //小于0表示未出现在屏幕上，不做任何处理
        if (currentArea <= 0) {
            return;
        }
        //刚要滑入和滑出时，异常状态的处理
        if (Math.abs(currentArea - lastArea) >= 100) {
            return;
        }
        if (currentArea < SDKConstant.VIDEO_SCREEN_PERCENT) {
            //进入自动暂停状态
            if (canPause) {
                pauseVideo(true);
                canPause = false;//滑动事件过滤
                //isFirst = true;
            }
            lastArea = 0;
            isFirst = true;
            mVideoView.setIsComplete(false); // 滑动出50%后标记为从头开始播
            mVideoView.setIsRealPaused(false);
            return;
        }

        if (isPauseBtnClick() || isComplete()) {
            //进入手动暂停或者播放结束，播放结束和不满足自动播放条件都作为手动暂停
            pauseVideo(false);
            canPause = false;
            return;
        }

        //满足自动播放条件或者用户主动点击播放，开始播放
        if (Utils.canAutoPlay(mContext, AdContextParameters.getCurrentSetting())
                || isPlaying()) {
            lastArea = currentArea;
            resumeVideo();
            canPause = true;
            mVideoView.setIsRealPaused(false);
        } else {
            pauseVideo(false);
            mVideoView.setIsRealPaused(true); //不能自动播放则设置为手动暂停效果
        }
    }

    public void destroy() {
        mVideoView.destroy();
        mVideoView = null;
        mContext = null;
        mXAdInstance = null;
    }

    /**
     * 实现play层接口
     */
    @Override
    public void onClickFullScreenBtn() {
        try {
            ReportManager.fullScreenReport(mXAdInstance.event.full.content, getPosition());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mParentView.removeView(mVideoView);
        VideoFullDialog dialog = new VideoFullDialog(mContext, mVideoView, mXAdInstance,
                mVideoView.getCurrentPosition());
        dialog.setListener(new VideoFullDialog.FullToSmallListener() {
            @Override
            public void getCurrentPlayPosition(int position) {
                backToSmallMode(position);
            }

            //播放完毕后暂停
            @Override
            public void playComplete() {
                bigPlayComplete();
            }
        });
        dialog.setSlotListener(mSlotListener);
        dialog.show();
    }

    private void backToSmallMode(int position) {
        if (mVideoView.getParent() == null) {
            mParentView.addView(mVideoView);
        }
        isFirst = false; //防止多发送一次sus
        mVideoView.isShowFullBtn(true);//显示全屏按钮
        mVideoView.mute(true);//小屏视频静音
        mVideoView.setListener(this);//重新设置监听为业务逻辑层
        mVideoView.seekAndResume(position);//是播放器跳到指定位置并播放
        canPause = true; // 标为可自动暂停
    }

    /**
     * @name bigPlayComplete
     * @function 全屏播放结束调用方法
     * @author ArnoFrost
     * @time 2017/12/14 0014  15:37
     */
    private void bigPlayComplete() {
        //判断VideoView是否有Parent如果没有,添加到父容器
        if (mVideoView.getParent() == null) {
            mParentView.addView(mVideoView);
        }
        mVideoView.isShowFullBtn(true);//显示全屏按钮
        mVideoView.mute(true);//小屏视频静音
        mVideoView.setListener(this);//重新设置监听为当前对象
        mVideoView.seekAndPause(0);//是播放器跳到指定位置并暂停
        canPause = false;
    }

    @Override
    public void onClickVideo() {
        String desationUrl = mXAdInstance.clickUrl;
        if (mSlotListener != null) {
            if (mVideoView.isFrameHidden() && !TextUtils.isEmpty(desationUrl)) {
                mSlotListener.onClickVideo(desationUrl);
                try {
                    ReportManager.pauseVideoReport(mXAdInstance.clickMonitor, mVideoView.getCurrentPosition()
                            / SDKConstant.MILLION_UNIT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            //走默认样式
            if (mVideoView.isFrameHidden() && !TextUtils.isEmpty(desationUrl)) {
                Intent intent = new Intent(mContext, AdBrowserActivity.class);
                intent.putExtra(AdBrowserActivity.KEY_URL, mXAdInstance.clickUrl);
                mContext.startActivity(intent);
                try {
                    ReportManager.pauseVideoReport(mXAdInstance.clickMonitor, mVideoView.getCurrentPosition()
                            / SDKConstant.MILLION_UNIT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //返回
    @Override
    public void onClickBackBtn() {
    }

    //播放
    @Override
    public void onClickPlay() {
        sendSUSReport(false);
    }

    //加载成功
    @Override
    public void onAdVideoLoadSuccess() {
        if (mSlotListener != null) {
            mSlotListener.onAdVideoLoadSuccess();
        }
    }

    //加载失败
    @Override
    public void onAdVideoLoadFailed() {
        if (mSlotListener != null) {
            mSlotListener.onAdVideoLoadFailed();
        }
        //加载失败全部回到初始状态
        canPause = false;
    }

    //播放结束
    @Override
    public void onAdVideoLoadComplete() {
        try {
            ReportManager.sueReport(mXAdInstance.endMonitor, false, getDuration());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mSlotListener != null) {
            mSlotListener.onAdVideoLoadComplete();
        }

        //标记为不能从头播放，只有滑出50%以后，才会标记为可以从头开始
        //canPlayBack = false;
        //isClickPlay = false;
        mVideoView.setIsRealPaused(true);
    }

    @Override
    public void onBufferUpdate(int time) {
        try {
            ReportManager.suReport(mXAdInstance.middleMonitor, time / SDKConstant.MILLION_UNIT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int getPosition() {
        return mVideoView.getCurrentPosition() / SDKConstant.MILLION_UNIT;
    }

    private int getDuration() {
        return mVideoView.getDuration() / SDKConstant.MILLION_UNIT;
    }

    /**
     * 发送SUS监测
     *
     * @param isAuto
     */
    private void sendSUSReport(boolean isAuto) {
        try {
            ReportManager.susReport(mXAdInstance.startMonitor, isAuto);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //传递消息到appcontext层
    public interface VideoSDKSlotListener {

        public ViewGroup getAdParent();

        public void onAdVideoLoadSuccess();

        public void onAdVideoLoadFailed();

        public void onAdVideoLoadComplete();

        public void onClickVideo(String url);
    }
}
